Skip to content

Latest commit

 

History

History
73 lines (65 loc) · 1.78 KB

File metadata and controls

73 lines (65 loc) · 1.78 KB

203. Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.

Example:

Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5 

Solutions (Python)

1. Two Pointers

# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = NoneclassSolution: defremoveElements(self, head: ListNode, val: int) ->ListNode: pre, cur=None, headwhilecur: ifcur.val==val: ifpre: pre.next=cur.nextelse: head=cur.nextelse: pre=curcur=cur.nextreturnhead

2. Add a New Head

# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = NoneclassSolution: defremoveElements(self, head: ListNode, val: int) ->ListNode: cur=ListNode(0) cur.next=headhead=curwhilecurandcur.next: ifcur.next.val==val: cur.next=cur.next.nextelse: cur=cur.nextreturnhead.next

3. Recursion

# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = NoneclassSolution: defremoveElements(self, head: ListNode, val: int) ->ListNode: ifnothead: returnNoneelifhead.val==val: returnself.removeElements(head.next, val) else: head.next=self.removeElements(head.next, val) returnhead
close